/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nanosn.coffeemaker.application.commands.generate;

import com.nanosn.coffeemaker.Project;
import com.nanosn.coffeemaker.application.commands.generate.util.Helper;
import com.nanosn.coffeemaker.freemarker.FMPP;
import com.nanosn.util.Jar;
import com.nanosn.util.parsers.commandline.Command;
import java.io.File;
import java.util.Map;

/**
 *
 * @author selkhateeb
 */
public class ModelsAPI implements Command {

    private String getApplicationName(String[] args) throws Exception {
        if (args.length < 2) {
            throw new Exception("Application Name not specified");
        }
        return args[1].toLowerCase();
    }

//    private ClassName[] getClassNames() throws Exception {
//
//        Class[] classes = Project.getClassLoader().getModelClasses();
//
//        ArrayList<ClassName> stringClasses = new ArrayList<ClassName>();
//
//        for (Class class1 : classes) {
//            stringClasses.add(new ClassName(class1.getSimpleName()));
//        }
//
//        return stringClasses.toArray(new ClassName[stringClasses.size()]);
//    }

    @Override
    public void run(String[] args) throws Exception {
        /*
        - rootPackage
        - applicationName
        - classNames
        - directory
         */
        final String projectDir = Project.PWD;

        String srcFile = Project.TEMPLATE_FILES_PACKAGE_DIRECTORY
                         + File.separator + "database"
                         + File.separator + "api.java.ftl";

        /* To generate the Settings file we do not need to pass any variables
         * However, for the manage.sh we need to determine the location
         * of the Main class .. or the Jar file
         */
        Map<String, Object> variables = Helper.getVariables(getApplicationName(args));
//
//        String dir = Project.getSettings().getRootPackage() + "." + getApplicationName(args);
//        variables.put("classNames", getClassNames());
//        variables.put("applicationName", getApplicationName(args));
//        variables.put("directory", dir.replace(".", "/"));
//        variables.put("rootPackage", Project.getSettings().getRootPackage());

        if (!Project.getApplicationJar().isDirectory()) {

            String tmpFile = Project.TMP + Project.TEMPLATE_FILES_PACKAGE_DIRECTORY
                             + File.separator + "database"
                             + File.separator + "api.java.ftl";
            //Extract files to temp directory
            Jar.ExtractSingleFile(Project.getApplicationJar(), srcFile, tmpFile);
            FMPP.RunFMPP(tmpFile, projectDir, variables);
        }
        else {
            FMPP.RunFMPP(srcFile, projectDir, variables);
        }
    }

    @Override
    public String getHelp() {
        return "Generates the models api";
    }
}
